package nl.hva.three2learn.model;

import java.io.Serializable;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.persistence.OrderColumn;
import javax.persistence.Table;

import org.hibernate.annotations.LazyCollection;
import org.hibernate.annotations.LazyCollectionOption;
import org.hibernate.annotations.OrderBy;

@Table(name = "topic")
@Entity
public class Topic implements Serializable {

	/**
	 * 
	 */
	private static final long serialVersionUID = 2965287551341827841L;

	@Id
	@GeneratedValue
	@Column(name = "topic_id")
	private long id;

	@ManyToOne
	private Course course;

	@Column(name = "title")
	private String title;

	@Column(name = "date")
	private Date date;

	@ManyToOne
	@LazyCollection(LazyCollectionOption.FALSE)
	private User owner;

	@OneToMany
    @javax.persistence.OrderBy(value="id")
	@LazyCollection(LazyCollectionOption.FALSE)
	private List<Post> posts;

	public Topic() {
	}

	public Topic(Course course, String title, User owner) {
		this.course = course;
		this.title = title;
		this.owner = owner;
		posts = new LinkedList<Post>();
	}

	public long getId() {
		return id;
	}

	public void setId(long id) {
		this.id = id;
	}

	public Course getCourse() {
		return course;
	}

	public void setCourse(Course course) {
		this.course = course;
	}

	public String getTitle() {
		return title;
	}

	public void setTitle(String title) {
		this.title = title;
	}

	public Date getDate() {
		return date;
	}

	public void setDate(Date date) {
		this.date = date;
	}
	public User getOwner() {
		return owner;
	}

	public void addPost(Post toBeAdded) {
		posts.add(toBeAdded);
	}

	public void editPost(long postId, String text) {
		for (int i = 0; i < posts.size(); i++) {
			if (posts.get(i).getId() == postId) {
				posts.get(i).setText(text);
			}
		}

	}

	public Post getPostById(long postId) {
		for (int i = 0; i < posts.size(); i++) {
			Post toBeReturned = posts.get(i);
			if (toBeReturned.getId() == postId) {
				return toBeReturned;
			}
		}
		return null;
	}
	
	 public Post getFirstPost() {
		return posts.get(0);
	}

	public List<Post> getPosts() {
		return posts;
	}
}
